﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Core.BOL;
using Core.DAL;
using Core.Extentions;

namespace ScoutNET.Routes
{
    public class SubdomainRoute : RouteBase
    {
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData returnValue = null;
           
            // Retrieve the url - and split by dots:
            var url = httpContext.Request.Headers["HOST"];
            // Get the subdomain (as a string):
            int index = url.IndexOf(".");

            if (index != -1 && httpContext.Request.AppRelativeCurrentExecutionFilePath == "~/")
            {
                string subDomain = url.Substring(0, index).ToLower();

                SectionRepository sr = new SectionRepository();
                tSite_Section s = sr.GetSectionsBySystemName(subDomain);
                if (s != null)
                {
                    returnValue = new RouteData(this, new MvcRouteHandler());
                    returnValue.Values.Add("controller", "Section");
                    returnValue.Values.Add("action", "Index");
                    returnValue.Values.Add("systemName", s.SystemName.UppercaseFirst());
                }
               
            }
           
            return returnValue;
        }

        /// <summary>
        /// Required override. Just return null ;)
        /// </summary>

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            return null;
        }
    }
}
